from logging.handlers import RotatingFileHandler

import os
from flask import Flask,render_template
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from config import  config

import logging

redis_store=None
db=SQLAlchemy()
basedir = os.path.abspath(os.path.dirname(__file__))

def create_app(config_name):
    set_up_log(config_name)
    #创建应用
    app=Flask(__name__)
    #加载配置文件
    app.config.from_object(config[config_name])
    #初始化mysql
    db.init_app(app)
    app.config['SQLALCHEMY_DATABASE_URI']=config[config_name].SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=config[config_name].SQLALCHEMY_TRACK_MODIFICATIONS
    #初始化redis
    global redis_store
    redis_store=StrictRedis(config[config_name].REDIS_HOST,config[config_name].REDIS_PORT)
    #设置session
    Session(app)
    #注册蓝图
    from information.modules.index import index_blu
    app.register_blueprint(index_blu,url_prefix='')
    from information.modules.passport import passport_blu
    app.register_blueprint(passport_blu, url_prefix='/passport')
    from information.modules.news import news_blu
    app.register_blueprint(news_blu, url_prefix='/news')
    from information.modules.user import user_blu
    app.register_blueprint(user_blu, url_prefix='/user')
    from information.modules.profile import profile_blu
    app.register_blueprint(profile_blu, url_prefix='/profile')
    from information.modules.admin import admin_blu
    app.register_blueprint(admin_blu, url_prefix='/admin')
    print(app.url_map)
    from information.modules import index_class
    app.add_template_filter(index_class,'index_class')
    return app

def set_up_log(config_name):
    # 设置日志的记录等级
    logging.basicConfig(level=config[config_name].DEBUG)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)